#!/bin/bash
# CodeBuddy Craft 启动脚本
# 作者: ZhangQing
# 日期: 2025-08-12

echo "==================================="
echo " CodeBuddy Craft 启动脚本"
echo "==================================="

# 设置环境变量
export PYTHONPATH=$(pwd)
export ENVIRONMENT=production
export PORT=8000

# 检查Python环境
if ! command -v python3 &> /dev/null; then
    echo "[错误] 未找到Python，请安装Python 3.9+"
    exit 1
fi

# 检查虚拟环境
if [ ! -f "venv/bin/activate" ]; then
    echo "[信息] 创建虚拟环境..."
    python3 -m venv venv
    if [ $? -ne 0 ]; then
        echo "[错误] 创建虚拟环境失败"
        exit 1
    fi
fi

# 激活虚拟环境
echo "[信息] 激活虚拟环境..."
source venv/bin/activate

# 安装依赖
echo "[信息] 检查依赖..."
pip install -r requirements.txt
if [ $? -ne 0 ]; then
    echo "[警告] 安装依赖失败，尝试继续..."
fi

# 创建必要的目录
mkdir -p data logs temp

# 检查数据库
echo "[信息] 检查数据库..."
python -c "from backend.database.connection import init_db; import asyncio; asyncio.run(init_db())"
if [ $? -ne 0 ]; then
    echo "[警告] 数据库初始化失败，尝试继续..."
fi

# 启动应用
echo "[信息] 启动应用..."
echo "[信息] 访问地址: http://localhost:$PORT"
python main.py

# 退出
echo "[信息] 应用已关闭"